package org.gap.jseed.annotation;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import org.gap.jseed.util.AnnotationExtractor;

public class LoggingHandler implements InvocationHandler {
	private static final String PARAMETER = "@";
	private static final String NAME = "@name";
	private Log.Severity level;
	private String message;
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		
		if (message == null) {
			Log logAnno = AnnotationExtractor.getAnnotation(proxy, method, Log.class);
			message = logAnno.message();
			level = logAnno.level();
		}
		String modifiedMessage = modifyMessage(method.getName(), args);
		switch(level) {
		case DEBUG:
			System.out.println("DEBUG: " + modifiedMessage);
			break;
		case INFO:
			System.out.println("INFO: " + modifiedMessage);
			break;
		case WARNING:
			System.err.println("WARNING: " + modifiedMessage);
			break;
		case ERROR:
			System.err.println("ERROR: " + modifiedMessage);
		}
		
		return null;
	}

	private String modifyMessage(String name, Object[] args) {
		String result = message.replace(NAME, name);
		
		for (int i = 0; i < args.length; i++) {
			result = result.replace(PARAMETER + (i + 1), "" + args[i]);
		}
		
		return result;
	}

}
